package relu.fbs;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

import jfm.lp.LPX;
import jfm.model.*;
import jfm.model.Types.*;

import relu.fbs.jfm.JFMFarmData.JFMFarmDatum;
import relu.fbs.jfm.JFMFarmData;
import relu.fbs.jfm.AbstractJFMCropData.JFMCDatum;

public class SimConstrained {

	/** Takes 4 arguments 
	 * @param 0 The fbs data file 
	 * @param 1 The xml farm data file 
	 * @param 2 the output file 
	 * */
	public static void main (String args[]) {
		Farm nextFarm=null;
		JFMFarmData jfmFarm=null;
		try {
			BufferedReader dataReader = new BufferedReader(new FileReader("./data/"+args[0]));
			Farm baseFarm = Farm.fromXML("./xml/"+args[1]);
			String jobName = args[1].split("\\.")[0]+"_"+args[2];
			System.out.println("Running Job "+jobName);
			OutputWriter out=new OutputWriter(baseFarm,new FileWriter("./out/"+jobName+".csv"));
			FileWriter errout=new FileWriter("./out/"+jobName+".err");
			String farmLine = dataReader.readLine(); // The header 
			farmLine=dataReader.readLine();
			out.printHeader();
			while(farmLine!=null){
				try {
				jfmFarm = JFMFarmData.fromCSVLine(farmLine);
				nextFarm = ToJFM.buildConstrained(baseFarm,jfmFarm,0.1,	false);
				System.out.println(nextFarm.toString());
				LPX status = nextFarm.solve(true);
				if ( status == LPX.LPX_OPT ){
					out.printSolution(jfmFarm,nextFarm);
					System.out.println(Output.oneLineSummary(nextFarm));
					Output.profitSummary(nextFarm, true);

					out.flush();
				} else {
					errout.write("Optimal Solution not found for "+jfmFarm.farmId+"\n");
					errout.flush();
					throw new Error("Culprit is "+jfmFarm);
				}
				} catch (BadModelException ex){
					System.out.println("Warning: "+ex.getMessage());
				}
				farmLine=dataReader.readLine();
			}
			out.close();
			errout.close();
		} catch (FileNotFoundException ex){
			throw new Error(ex.getMessage());
		} catch (IOException ex){
			throw new Error(ex.getMessage());		
		} catch (GLPKException ex){
			throw new Error(ex.getMessage()+"\n"+jfmFarm.toString()+"\n"+ex.getMessage());
		} 
	}
	
}
